<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('distributedEnter.pageTitle')" @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="page-auto-noheight paddingbottom">
				<!-- 调拨单信息 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedOut.informationOut') }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.orderBring')
						}}：</text>{{ data.enterDetails.docNo }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.date')
						}}：</text>{{ data.enterDetails.stepOutDate }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.transferOutQty')
						}}：</text>{{ data.enterDetails.totalOutQty }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('pageTranslation.qtyTransferred')
						}}：</text>{{ data.enterDetails.totalInQty }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.surplusQty')
						}}：</text>{{ data.enterDetails.surplusQty || 0 }} <!-- remainQTy -->
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.scannedQuantity')
						}}：</text>{{ totalScanNum || 0 }}
					</view>
				</view>
				<!-- 扫描条码 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barcode"
							:placeholder="$t('stockManage.pleaseScanCode')" type="search" @confirm="confirm"
							@iconClick="iconClick">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('distributedOut.warehouse') }}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.organizationEnterList"
							:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="value"
							v-model="data.selectId" @select="selectOut"></superweiCombox>
					</view>
					<view class="custom-card-itemTwo">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('distributedOut.location') }}：</text>
						<text style="color: #1492dd;font-weight: 600;">{{ data.locationId }}</text>
						<!-- <storageBin :ignoreLocationCode="data.ignoreLocationCode" class="gui-text-right"
							requestUrl="/api1/wms/warehouse/QueryLocation"
							:requestParam="data.requestParam" :locationUseList="data.locationUseList"
							@setClick="getClick"></storageBin> -->
					</view>
					<view class="gui-form-item" style="font-size: 26rpx;">
						<text class="gui-form-label item-info-title" style="width:300rpx;">{{
							$t('JsInternational.onWay')
							}}</text>
						<view class="gui-form-body gui-text-right" style="padding-right: 20rpx;">
							{{ data.oddTotalPathLossNum || 0 }}
						</view>
					</view>
				</view>
				<!-- 当前扫描条码 -->
				<view class="custom-form-card" v-if="data.currentBarcode">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCoded')
									}}：</text>{{ data.currentBarcode.barcode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec')
									}}：</text>{{ data.currentBarcode.materialSpec }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCode')
									}}：</text>{{ data.currentBarcode.materialCode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialName')
									}}：</text>{{ data.currentBarcode.materialName }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.qty')
										}}：</text>{{ data.currentBarcode.currentQty }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom')
										}}：</text>{{ data.currentBarcode.unit }}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedOut.organizationOut')
									}}：</text>{{ data.currentBarcode.barcode ?
											'国内' : '' }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedOut.organizationIn')
									}}：</text>{{ data.currentBarcode.barcode ?
											'墨西哥' : '' }}
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('materials.distributedManner') }}</text>
					<view class="gui-title-line"></view>
				</view>
				<uni-card class="element-auto gui-margin-top card-my"
					style="width: 100%;margin: 0;padding: 0 !important;">
					<view class="element-auto" style="height: 300rpx;padding: 0 !important;">
						<zb-table :columns="data.column1" :stripe="true" @rowClick="rowClick" :border="true"
							:data="tableData.list" @customLook="customBtnFn" :cell-style="cellStyle"
							:cell-header-style="cellHeaderStyle">
						</zb-table>
					</view>
				</uni-card>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">
						{{ $t('calendar.submit') }}
					</view>
				</view>
			</view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup" type="center">
				<view class="input-dialog-box"
					style="padding: 40rpx 20rpx 20rpx 20rpx;border-radius: 22rpx;width: 600rpx;">
					<uni-icons class="popup-close-icons" type="closeempty" color="#9C9C9C" size="26"
						@click="closePopup"></uni-icons>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialCoded')
						}}：</text>{{ data.popupInfo.materialCode }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialName')
						}}：</text>{{ data.popupInfo.materialName
							}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialSpec')
						}}：</text>{{ data.popupInfo.materialSpec
							}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{ data.popupInfo.unit }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.overallQty')
						}}：</text>{{ data.popupInfo.outQty }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('materials.quantityInStorage')
						}}：</text>{{ data.popupInfo.inQty }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('JsInternational.onWay')
						}}：</text>{{ data.popupInfo.totalPathLossNum }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.scannedQuantity')
						}}：</text>{{ data.popupInfo.currentScanQty }}
					</view>
				</view>
			</uni-popup>
			<!-- 页面弹窗 -->
			<uni-popup ref="inputDialog" type="center">
				<view class="input-dialog-box">
					<view class="input-dialog-content">
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialCode') }}:{{ data.currentBarcode.materialCode }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialName') }}:{{ data.currentBarcode.materialName }}
						</view>
						<view class="input-dialog-item" style="font-weight: 600;">
							{{ $t('distributedOut.location') }}：{{ data.currentBarcode.locationCode }}
						</view>
						<view class="input-dialog-item flexclass">
							<view>{{ $t("materials.scanQty") }}：</view>
							<view class="input-dialog-item-count">
								<input v-model="data.currentBarcode.inputCurrentQty" type="number"
									:placeholder="$t('distributedEnter.pleaseMaterialQty')" @confirm="qtyInput" />
							</view>
						</view>
						<view class="input-dialog-item flexclass">
							<view>{{ $t('JsInternational.onWay') }}：</view>
							<view class="input-dialog-item-count">
								<input v-model="data.currentBarcode.pathLossNum" type="number" @confirm="onWayInput"
									@input="onInput" :placeholder="$t('distributedEnter.damageQty')" />
							</view>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('calendar.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="confirmFn">
							{{ $t('calendar.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import { reactive, ref, onMounted, computed, watch, toRaw, toRef } from 'vue';
import { getDataDictionaryFn, pitchOnFn, sortClass } from '@/utils/index.js'
import { findStepoutHById, scanStepInBarcodeNew, distributedCallInNew, cancelOccupy } from '@/api/api.js'
import superweiCombox from '@/components/superweiCombox';
import tableColor from '@/hooks/tableColor.js'
import storageBin from '@/components/storageBin.vue'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_SCAN, OPERATION_LOOK, OPERATION_COMMIT } from '@/constant/index.js'
import { useStore } from "vuex";
import { onBackPress } from '@dcloudio/uni-app';
import pdaScan from '@/hooks/pdaScan.js'

import { toFixed4 } from '@/utils/index.js';

//国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

let store = useStore()
const { scan } = pdaScan()

components: {
	storageBin,
		superweiCombox
}
let { tableData } = tableColor();
const { cellStyle, cellHeaderStyle } = tableColor();
const props = defineProps({
	id: String
})
let popup = ref(null)
let inputDialog = ref(null)

let data = reactive({
	value: ['0'],
	selectedText: '',
	selectId: '',
	wareHouseId: '',
	organizationEnterList: [],
	locationId: '',
	locationCode: '',
	currentLocationInfo: {}, //当前选中库位信息
	barcode: '',
	column1: [{
		name: 'age',
		type: 'ailibtn',
		label: t('translationImage.operation'),
		scanValue: '',
		fixed: true,
		width: 80,
	},
	{
		name: 'materialCode',
		label: t('distributedEnter.materialCode'),
		fixed: true,
		width: 100,
		emptyString: '--'
	},
	{
		name: 'materialName',
		label: t('distributedEnter.materialName'),
	},
	{
		name: 'materialSpec',
		label: t('distributedEnter.materialSpec'),
		width: 200,
	},
	{
		name: 'unit',
		label: t('distributedEnter.uom'),
		width: 60,
	},
	{
		name: 'outQty',
		label: t('distributedEnter.overallQty'),
		width: 60,
	},
	{
		name: 'inQty',
		label: t('materials.quantityInStorage'),
		width: 100,
	},
	{
		name: 'currentScanQty',
		label: t('distributedEnter.scannedQuantity'),
		width: 120,
	},
	{
		name: 'totalPathLossNum',
		label: t('distributedEnter.intransDamageQty')
	}
	],
	requestParam: {
		warehouseCode: 'RM',
		warehouseId: 0,
		warehouseName: '',
		locationCode: '',
		locationName: '',
		locationTypeCode: '',
		locationTypeName: '',
		forbiddenStatus: '',
		areaCode: ''
	},
	ignoreLocationCode: [], //前端算满的库位
	enterDetails: {},
	currentBarcode: {}, //当前barcode
	locationUseList: [
		// {
		// 	locationCode:'', //库位code
		// 	surplusCapacity:0, //后端告诉前端容量
		// 	barcodeList:[], //当前库位本次扫描绑定的barcode条码集合
		// 	currentCapacity:0, //后端容量减去本次扫描绑定条码的剩余容量  前端预算容量
		// }
	], //当前用户使用库位情况
	popupInfo: {}, //当前行的弹窗信息
	doubleArray: {} //物料纬度的barcode条码
})

onMounted(() => {
	uni.$on('scancodedate', (res) => {
		console.log('获取到的code：' + res.code)
		getCode(res.code, 'pda')
	})
	getInitData();
	findStepoutHByIdFn()
})
// 根据id查询调入单详情
const findStepoutHByIdFn = () => {
	let parmes = {
		id: props.id
	}
	findStepoutHById(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '分布式调入'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code, //返回状态
				errorMessage: res.msg, //错误信息
				isPass: res.code == 0 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_LOOK,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		if (res.code == 0) {
			data.enterDetails = res.data;
			//计算剩余数量
			const scanNum = totalScanNum.value > 0 ? totalScanNum.value : 0
			data.enterDetails.surplusQty = (Number(data.enterDetails.totalOutQty) - Number(data.enterDetails.totalInQty) - Number(scanNum)).toFixed(4)
			tableData.list = res.data.wmsStepOutDetails
			tableData.list.forEach(x => {
				x.currentScanQty = 0
				x.pathLossNum = 0
				x.totalPathLossNum = 0
			})
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	})
}

data.barcodeList = computed(() => {
	return store.state.transferredList
})

const totalScanNum = computed(() => {
	let total = 0;
	data.barcodeList.forEach(x => {
		total += Number((Number(x.currentQty).toFixed(4)))
	})
	return total.toFixed(4)
})

//计算剩余数量
watch(() => data.barcodeList, (newval, oldval) => {
	//计算剩余数量
	const scanNum = totalScanNum.value > 0 ? totalScanNum.value : 0
	data.enterDetails.surplusQty = (Number(data.enterDetails.outSumQty) - Number(data.enterDetails.inSumQty) - Number(scanNum)).toFixed(4)
}, {
	immediate: true,
	deep: true
})

//整个调入单的途损数量
data.oddTotalPathLossNum = computed(() => {
	let total = 0
	tableData.list.forEach(x => {
		total += x.totalPathLossNum
	})
	return toFixed4(total)
})

// 计算库位逻辑
const calculateLocationCode = (newVal) => {
	let tepData = toRaw(newVal)
	// 先清空,后续追加
	data.locationUseList.forEach(l => {
		l.barcodeList = []
	})
	// 追加
	tepData.forEach(x => {
		data.locationUseList.forEach(k => {
			if (x.locationCode == k.locationCode) {
				k.barcodeList.push(x.barcode)
				k.surplusCapacity = k.currentCapacity - k.barcodeList.length
			}
		})
	})
	//算满库位变量置空
	data.ignoreLocationCode = []
	// 把前端预算容量算出为0的库位抽出
	data.locationUseList.forEach(x => {
		if (x.surplusCapacity == 0) {
			data.ignoreLocationCode.push(x.locationCode)
		}
	})
}

function f(a, b) { //排序函数
	return (b.id - a.id); //返回比较参数
}

//把扫描条码变为物料集合的二维数组
watch(() => data.barcodeList, (newVal, oldVal) => {
	let tepData = toRaw(newVal)
	let list = sortClass(tepData)
	let tepList = []
	if (list.length) {
		list.forEach(x => {
			let item = {
				child: [],
				currentQty: 0,
				totalPathLossNum: 0
			}
			x.forEach(k => {
				item.materialCode = k.materialCode
				item.materialName = k.materialName
				item.materialSpec = k.materialSpec
				item.unit = k.unit
				item.currentQty += Number(k.currentQty)
				item.totalPathLossNum += Number(k.pathLossNum)
				item.isContinue = true
				item.child.push(k)
			})
			tepList.push(item)
		});
		tableData.list.sort(f); //这一步是进行排序
		tableData.list.map((item, index) => {
			if (item.materialCode == data.currentBarcode.materialCode) {
				tableData.list.unshift(tableData.list.splice(index, 1)[0]);
			}
		})
		var sortArr = []
		tableData.list.forEach(x => {
			if (sortArr.some(m => m.materialCode == x.materialCode)) {

			}
			else {
				sortArr.push(x)
			}
		})
		tableData.list.forEach(x => {
			tepList.forEach(k => {
				if (k.materialCode == x.materialCode && k.isContinue == true) {
					console.log(k.totalPathLossNum)
					let outQty = x.outQty //调出明细数量
					let inQty = x.inQty //已调入数量
					let leaveQty = Number(outQty - inQty) - x.currentScanQty
					let canAllowQty = 0;
					if (sortArr.some(m => m.id == x.id)) {
						x.totalPathLossNum = k.totalPathLossNum

					}
					if (leaveQty == 0) {
						k.currentQty -= x.currentScanQty //这里需要减去已经分配的
					} else if (leaveQty >= k.currentQty) {
						canAllowQty = k.currentQty
						tepList.forEach(h => {
							if (h.materialCode == k.materialCode) {
								k.isContinue = false;
							}
						})

						x.currentScanQty = canAllowQty
						k.currentQty -= x.currentScanQty //这里需要减去已经分配的
					} else {
						var cqty = k.currentQty - x.currentScanQty
						if (cqty <= leaveQty) {
							canAllowQty = cqty
						}
						else {
							canAllowQty = leaveQty
						}

						tepList.forEach(h => {
							if (h.materialCode == k.materialCode) {
								k.isContinue = true;
							}
						})
						x.currentScanQty += canAllowQty
						k.currentQty -= x.currentScanQty //这里需要减去已经分配的
					}
				}

			})
		})

		data.doubleArray = tepList;
	} else {
		tableData.list.forEach(x => {
			x.currentScanQty = 0
			x.totalPathLossNum = 0
		})
		data.currentBarcode = null
	}

	calculateLocationCode(newVal)

}, {
	immediate: true,
	deep: true
});

// 途损数量
const onWayInput = (e) => {
	var {
		value
	} = e.detail
	if (value.length > 0) {
		if (Number(value) > Number(data.currentBarcode.currentQty)) {
			uni.showToast({
				title: t('materials.damageCannot'),
				icon: 'none'
			})
			value = data.currentBarcode.currentQty
		}
		data.currentBarcode.pathLossNum = value
		data.currentBarcode.inputCurrentQty = toFixed4(data.currentBarcode.currentQty - value)
	}
}

const onInput = (e) => {
	var {
		value
	} = e.detail
	if (value.length > 0) {
		if (Number(value) > Number(data.currentBarcode.currentQty)) {
			uni.showToast({
				title: t('materials.damageCannot'),
				icon: 'none'
			})
			value = data.currentBarcode.currentQty
		}
		data.currentBarcode.pathLossNum = value
		data.currentBarcode.inputCurrentQty = toFixed4(data.currentBarcode.currentQty - value)
	}
}

const qtyInput = (e) => {
	var {
		value
	} = e.detail
	if (value.length > 0) {
		if (Number(value) > Number(data.currentBarcode.currentQty)) {
			uni.showToast({
				title: t('materials.enteredQuantityCannotBe'),
				icon: 'none'
			})
			value = data.currentBarcode.currentQty
		}
		data.currentBarcode.inputCurrentQty = value
		data.currentBarcode.pathLossNum = toFixed4(data.currentBarcode.currentQty - value)
	}
}

// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击搜索
const confirm = () => {
	getCode(data.barcode, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	// 判断这个托盘本次有没有绑定过
	console.log(data.barcodeList, 'data.barcodeList')
	let isBind = data.barcodeList.some(x => x.barcode == code);
	if (isBind) {
		uni.showToast({
			title: t('JsInternational.scanned'),
			icon: 'none'
		})
		return
	}
	if (!data.selectId) {
		uni.showToast({
			title: t('pageTranslation.plsChooseWarehous'),
			icon: 'none'
		})
		return
	}
	// if (!data.locationId) {
	// 	uni.showToast({
	// 		title: t('pageTranslation.plsChooseLocatoinFirstly'),
	// 		icon: 'none'
	// 	})
	// 	return
	// }
	// 判断当前用户选择的库位有没有容量
	if (data.ignoreLocationCode.includes(data.locationId)) {
		uni.showToast({
			title: t('JsInternational.volumn'),
			icon: 'none'
		})
		return
	}
	if (!code) {
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'none'
		})
		return
	}
	let parmes = {
		barcode: code,
		selectType: 'stepIn',
		stepOutHId: props.id,
		stepOutNo: data.enterDetails.docNo
	}
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	scanStepInBarcodeNew(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '分布式调入'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code, //返回状态
				errorMessage: res.msg, //错误信息
				isPass: res.code == 0 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		// console.log(res)
		if (res.code == 0) {
			//隐藏加载框
			uni.hideLoading();
			// 判断该条码对应的单据还剩多少数量
			let tep = tableData.list.filter(x => x.materialCode == res.data.materialCode);
			console.log(tep)
			let bool = tableData.list.some((item) => {
				return item.materialCode == res.data.materialCode
			})
			if (!bool) {
				uni.showToast({
					title: t('materials.materialIsNot'),
					icon: "none"
				});
				return
			}

			var sumoutQty = 0;
			var inQtyQty = 0;
			var sumScanQty = 0;
			if (tep.length) {
				for (var i = 0; i < tep.length; i++) {
					sumoutQty += tep[i].outQty
					inQtyQty += tep[i].inQty
					sumScanQty += tep[i].currentScanQty
				}

				// 筛选出和当前扫码一直的物料并提位
				if (tableData.list.length && tableData.list.length != 1) {
					for (var i = 0; i < tableData.list.length; i++) {
						var item = {}
						if (tableData.list[i].materialCode === res.data.materialCode) {
							item = tableData.list[i]
							tableData.list.splice(i, 1);
							tableData.list.unshift(item)
							break;
						}
					}
				}


				let num = Number(sumoutQty).toFixed(4) - Number(inQtyQty).toFixed(4) - Number(sumScanQty).toFixed(4); //

				num = toFixed4(num)
				if (num < 0) return uni.showToast({
					title: t('JsInternational.stockIn'),
					icon: 'none'
				})
				if (num - res.data.currentQty < 0) return uni.showToast({
					title: t('JsInternational.receiptStock'),
					icon: 'none'
				})
			}
			data.currentBarcode = res.data;
			data.locationId=res.data.wmsMaterialCapacity.locationCode
			data.locationCode=res.data.wmsMaterialCapacity.id
			data.currentBarcode.inputCurrentQty = toFixed4(data.currentBarcode.currentQty);
			data.currentBarcode.pathLossNum = 0;
			data.currentBarcode.locationCode = data.locationId;
			data.currentBarcode.locationId = data.locationCode;
			data.currentBarcode.warehouseCode = data.selectId;
			data.currentBarcode.wareHouseId = data.wareHouseId;
			data.currentBarcode.warehouseText = data.selectedText;
			console.log(data.currentBarcode);
			inputDialog.value.open();
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	})
}
const cancelFn = () => {
	let parmes = {
		locationCode: data.locationId,
		materialCode: data.currentBarcode.materialCode,
		id: data.currentBarcode.wmsMaterialCapacity.id,
		barcode: data.currentBarcode.barcode,
		locationName:data.currentBarcode.wmsMaterialCapacity.locationName,
	}
	cancelOccupy([parmes]).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '分布式调入-取消'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code, //返回状态
				errorMessage: res.msg, //错误信息
				isPass: res.code == 0 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		
		if (res.code == 0) {
			data.scanInfo = undefined
			data.locationId = ''
			inputDialog.value.close();
			uni.showToast({ title: t('fixedAssets.description'), icon: 'none', })
		} else {
			uni.showToast({ title: res.msg, icon: 'none', })
		}
	})
	// inputDialog.value.close();
}
const confirmFn = () => {
	let num = Number(data.currentBarcode.inputCurrentQty) + Number(data.currentBarcode.pathLossNum)
	if (num > data.currentBarcode.currentQty) {
		uni.showToast({
			title: t('JsInternational.greaterThan'),
			icon: 'none'
		})
		return
	}
	if (num < data.currentBarcode.currentQty) {
		uni.showToast({
			title: t('JsInternational.lessThan'),
			icon: 'none'
		})
		return
	}

	let isTrue = data.locationUseList.some(x => x.locationCode === data.locationId)
	if (!isTrue) {
		data.locationUseList.push({
			locationCode: data.currentLocationInfo.locationCode, //库位code
			surplusCapacity: Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo
				.usedInventory), //后端告诉前端容量
			barcodeList: [], //当前库位本次扫描绑定的barcode条码集合
			currentCapacity: Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo
				.usedInventory), //后端容量减去本次扫描绑定条码的剩余容量  前端预算容量
		})
	}
	data.currentBarcode.currentQty = toFixed4(data.currentBarcode.inputCurrentQty);
	// console.log(data.currentBarcode, 'data.locationUseList');
	store.commit('addTransferredList', data.currentBarcode)
	inputDialog.value.close();
}

// 提交
const submit = () => {
	if (!data.doubleArray.length) {
		uni.showToast({
			title: t('distributedOut.pleaseMaterial'),
			icon: 'none'
		});
		return
	}
	let stepInBarcodes = [];
	let arry = []
	data.doubleArray.forEach(x => {
		let item = {
			materialCode: x.materialCode,
			barcodeInfoVos: []
		}
		x.child.forEach(k => {
			var obj = {}
			obj.barcode = k.barcode;
			obj.id = k.id;
			obj.currentQty = k.inputCurrentQty;
			obj.numberOfLosses = k.pathLossNum;
			obj.wareHouseId = k.wareHouseId;
			obj.locationId = k.locationId;
			obj.locationCode = k.locationCode;
			obj.materialCode = k.materialCode;
			obj.wmsMaterialCapacity=k.wmsMaterialCapacity // 推荐库位的 
			stepInBarcodes.push(obj)
		})
		arry.push(item)

	})

	let parmes = {
		stepOutHId: props.id,
		sourceBillCode: data.enterDetails.docNo,
		lstBarcodeItem: stepInBarcodes
	}

	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});

	console.log('parmes', parmes)
	distributedCallInNew(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '分布式调入'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code, //返回状态
				errorMessage: res.msg, //错误信息
				isPass: res.code == 0 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		if (res.code == 0) {
			//隐藏加载框
			uni.hideLoading();
			uni.showToast({
				title: t('smashRemoval.submitSuccessfully'),
				icon: 'none'
			});
			store.commit('clearTransferredList')
			setTimeout(() => {
				uni.navigateBack()
			}, 800)
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	})
}

// 获取选中的库位id
const getClick = (x) => {
	console.log(x)
	data.currentLocationInfo = x;
	data.locationId = x.locationCode;
	data.locationCode = x.id
	// data.wareHouseId = x.warehouseId
}
const selectOut = (e) => {
	console.log(e)
	data.selectId = e.value;
	data.selectedText = e.text;
	// data.wareHouseId = e.id
}

const getInitData = async () => {
	// 获取调入组织仓库
	await getDataDictionaryFn('PDATransferInto').then(res => {
		data.organizationEnterList = res.data
	})
	let tepSelect1 = pitchOnFn(data.organizationEnterList)
	data.selectedText = tepSelect1[0].text
	data.selectId = tepSelect1[0].value
	// data.wareHouseId = data.organizationEnterList[0].id
}

// b表格的查看和取消
const customBtnFn = (item, index) => {
	console.log(item, index)
	data.popupInfo = item;
	popup.value.open()
}
const closePopup = () => {
	popup.value.close()
}
const rowClick = () => {

}

const clickRight = () => {
	navigate({
		url: '/pages/distributed/distributedEnterDetailNewRecord'
	})
}

onBackPress((options) => {
	if (options.from == 'backbutton') {
		navBackCheck()
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	navBackCheck()
}
const navBackCheck = () => {
	if (!data.barcodeList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				let arrList = []
				data.barcodeList.forEach(item => {
					arrList.push({
						locationName:item.wmsMaterialCapacity.locationName,
						locationCode: item.locationCode,
						materialCode: item.materialCode,
						id: item.wmsMaterialCapacity.id,
						barcode: item.barcode
					})
				})
				checks(arrList)
				// store.commit('clearTransferredList')
				// uni.navigateBack({
				// 	delta: 1
				// });
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}

// 大返回的时候取消库位
const checks = (item) => {
	cancelOccupy(item).then(res => {
		if (res.code == 0) {
			store.commit('clearTransferredList')
			uni.navigateBack({
				delta: 1
			});
		} else {
			uni.showToast({ title: res.msg, icon: "none", });
		}
	})
}
</script>

<style scoped lang="scss">
.uni-card__content,
.uni-card__content {
	padding: 0 !important;
}
</style>
